import 'dart:async';
import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

/// initParams: window.defaultRouteName : 对应从Native传过来的参数
void main() => runApp(MyApp(
      initParams: window.defaultRouteName,
    ));

class MyApp extends StatelessWidget {
  final String initParams;

  const MyApp({Key key, this.initParams}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter 混合开发',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or press Run > Flutter Hot Reload in a Flutter IDE). Notice that the
        // counter didn't reset back to zero; the application is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: "Flutter混合开发",nativeString: initParams,),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title,this.nativeString}) : super(key: key);

  final String nativeString;

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  static const EventChannel _eventChannelPlugin =
      EventChannel("EventChannelPlugin");

  static const MethodChannel _methodChannelPlugin =
      MethodChannel("MethodChannelPlugin");

  static const BasicMessageChannel<String> _basicMessageChannel =
      const BasicMessageChannel("BasicMessageChannelPlugin", StringCodec());

  String showMessage = " ";

  StreamSubscription _streamSubscription;

  bool _isMethodChannelPlugin = false;

  @override
  void initState() {
    _streamSubscription = _eventChannelPlugin
        .receiveBroadcastStream("传给Native的参数")
        .listen(_onToDart, onError: _onToDartError);

    // 使用BasicMessageChannel接受来自Native的消息，并向Native作回复
    _basicMessageChannel
        .setMessageHandler((String message) => Future<String>(() {
              setState(() {
                showMessage = "BasicMessageChannelPlugin" + message;
              });
              // 回复消息
              return "收到native的消息" + message;
            }));
    super.initState();
  }

  @override
  void dispose() {
    _streamSubscription.cancel();
    super.dispose();
  }

  /// 接收从native传过来的消息
  void _onToDart(message) {
    setState(() {
      showMessage = "EventChannelPlugin"+message;
    });
  }

  /// 错误日志
  void _onToDartError(error) {
    print(error.toString());
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Container(
        alignment: Alignment.topCenter,
        decoration: BoxDecoration(color: Colors.lightBlueAccent),
        margin: EdgeInsets.only(top: 70),
        child: Column(
          children: [
            SwitchListTile(
              value: _isMethodChannelPlugin,
              onChanged: _onChannelChange,
              title: Text(_isMethodChannelPlugin
                  ? "MethodChannelPlugin"
                  : "BasicMessageChannelPlugin"),
            ),
            TextField(
              onChanged: _onTextChange,
              decoration: InputDecoration(
                  focusedBorder: UnderlineInputBorder(
                      borderSide: BorderSide(color: Colors.white)),
                  enabledBorder: UnderlineInputBorder(
                      borderSide: BorderSide(color: Colors.white))),
            ),
            Text("初始化的消息：${widget.nativeString}"),
            Text("收到native的消息：$showMessage"),
          ],
        ),
      ),
    );
  }

  _onChannelChange(bool value) =>
      setState(() => _isMethodChannelPlugin = value);

  _onTextChange(String text) async {
    String response;
    try {
      if (_isMethodChannelPlugin) {
        // 使用MethodChannelPlugin接受来自Native的消息，并向Native作回复
        response = await _methodChannelPlugin.invokeMethod("send", text);
      } else {
        response = await _basicMessageChannel.send(text);
      }
    } on PlatformException catch (error) {
      print(error);
    }
  }
}
